﻿using MediatR;
using Traceable.App.Application.Command.Goods;
using Traceable.Domian;
using Traceable.ErrorCode;
using Traceable.Infastructure;

namespace Traceable.App.Application.Handler.Goods
{
    public class DeleteGoodsTraceHandler : IRequestHandler<DeleteGoodsTraceCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Traceable_Table> _traceableRepository;

        public DeleteGoodsTraceHandler(IBaseRepository<Traceable_Table> traceableRepository)
        {
            _traceableRepository = traceableRepository;
        }

        /// <summary>
        /// 删除溯源基本信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<int>> Handle(DeleteGoodsTraceCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();

            var traceable = _traceableRepository.GetAll().Where(p=>request.Id.Contains(p.Id)&&  p.IsDelete == false).ToList();
            if (traceable!=null)
            {
                foreach (var item in traceable)
                {
                    item.IsDelete = true;
                }
            }
            var res = _traceableRepository.UpdateRange(traceable);
            if (res > 0)
            {
                result.Code = StatusEnum.OK;
                result.Data = res;
                result.Message = "删除成功";
            }
            else
            {
                result.Code = StatusEnum.Fail;
                result.Data = res;
                result.Message = "删除失败";
            }
            return Task.FromResult(result);
        }
    }
}
